const Koa = require('koa');
const app = new Koa();
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const cors = require('koa2-cors');
const rest = require('./rest');
const session = require("koa-session2");
const store = require("./config/store.js");
const controls = require('./config/controller')();

// error handler
onerror(app);

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}));
app.use(logger());

// cors
app.use(cors({
    origin: 'http://localhost:8080',
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'OPTIONS'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept']
}));

// koa:sess
app.use(session({
    store: new store(),
    key: "SESSIONID",
}));

// logger
app.use(async (ctx, next) => {
    const start = new Date();
    await next();
    const ms = new Date() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});

// rest
app.use(rest.restify());

// routes
app.use(controls.routes(), controls.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

module.exports = app;
